package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    //联系人添加
    public void contacts(Long friendId) {
        Long userId = UserHolder.getUserId();
        //1. 将好友数据存到MongoDB
        friendApi.save(userId, friendId);
        //2. 将好友数据存到环信
        huanXinTemplate.addContact("hx" + userId, "hx" + friendId);
    }

    //查询好友列表
    public PageResult findFriends(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        List<Friend> list = friendApi.findByUserId(userId,page,pagesize);
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        // 获取所有好友id
        List<Long> friendIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds);
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            Long friendId = friend.getFriendId();
            UserInfo userInfo = map.get(friendId);
            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,0l,vos);
    }
}
